package com.example.chinesenation.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chinesenation.Entity.Article;
import com.example.chinesenation.Entity.Policy;
import com.example.chinesenation.Entity.Resources;
import com.example.chinesenation.Redis.RedisService;
import com.example.chinesenation.Response.ServerResponse;
import com.example.chinesenation.Service.IArticleService;
import com.example.chinesenation.Service.IPolicyListService;
import com.example.chinesenation.Service.IResourcesService;
import com.example.chinesenation.Utils.*;

import com.example.chinesenation.VO.MainData;
import com.example.chinesenation.VO.MainPage.VOArticleList;
import com.example.chinesenation.VO.MainPage.VOPolicyList;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sakuraFallingDown
 * @version 1.0
 * @date 2021/1/18 16:20
 */
@Controller
@ResponseBody
@RequestMapping("/main")
@CrossOrigin
public class MainController {//主页信息获取，包括推荐信息

    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private Audience audience;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private IPolicyListService policyListService;

    @Autowired
    private RecommendedTools recommendedTools;

    /**
     * @param token 用户的token信息
     * @return ServerResponse<MainData> 返回的MainData信息
     */
    @ApiOperation("整个系统主界面获取数据的接口")
    @PostMapping("/index")
    public ServerResponse<MainData> mainPage(@RequestHeader(value = "token",required = false)String token){

        MainData mainData=new MainData();
        List<VOPolicyList> mainPolicy = new ArrayList<>();
        List<VOArticleList> mainArticle = new ArrayList<>();
        List<Resources> resources = new ArrayList<>();
        if(token!=null&&!token.equals("")) {//登录了就去获取推荐内容
            String uid = JwtTokenUtil.getUserId(token, audience);//根据用户进行推荐
            mainArticle=recommendedTools.recommendedArticle(uid);
            mainPolicy=recommendedTools.recommendedPolicy(uid);
        }else {
            //游客推荐最新热门榜
            if (redisService != null) {//redis服务为空，连接不上redis服务器
                mainPolicy = (List<VOPolicyList>) redisService.get(CommonURL.MainPagePolicy);
                mainArticle = (List<VOArticleList>) redisService.get(CommonURL.MainPageArticle);
                resources = (List<Resources>) redisService.get(CommonURL.MainPageResources);
            }
            mainArticle = getRankArticle(mainArticle, articleService, redisService);
            mainPolicy = getRankPolicy(mainPolicy, policyListService, redisService);
            if (resources == null || resources.size() == 0) {
                resources = new ArrayList<>();
            }
        }
        mainData.setArticles(mainArticle);
        mainData.setPolicies(mainPolicy);
        mainData.setResources(resources);
        return ServerResponse.createSuccessResponse("获取主页信息成功",mainData);
    }

    /**
     * @param mainPolicy 从redis中获取的值
     * @param policyListService autowired自动注入的接口
     * @param redisService  redis服务
     * @return
     */
    static List<VOPolicyList> getRankPolicy(List<VOPolicyList> mainPolicy, IPolicyListService policyListService, RedisService redisService) {
        if (mainPolicy == null || mainPolicy.size() == 0) {
            mainPolicy = new ArrayList<>();
            IPage<Policy> iPage = new Page<>(1, 10);
            QueryWrapper<Policy> qw = new QueryWrapper<>();
            qw.orderByDesc("pageview");
            IPage<Policy> page = policyListService.page(iPage, qw);
            List<Policy> policies = page.getRecords();
            for (Policy policy : policies) {
                VOPolicyList voPolicyList = new VOPolicyList();
                DataChanges.fromPolicyToVOPolicyList(policy, voPolicyList);
                mainPolicy.add(voPolicyList);
            }
            if (mainPolicy.size() != 0) {
                redisService.put(CommonURL.MainPagePolicy, mainPolicy, 1);//放入redis缓存中
            }
        }
        return mainPolicy;
    }

    /**
     * @param articleLists 从redis中获取的值
     * @param articleService autowired自动注入的接口
     * @param redisService redis服务
     * @return
     */
    static List<VOArticleList> getRankArticle(List<VOArticleList> articleLists, IArticleService articleService, RedisService redisService) {
        if (articleLists==null||articleLists.size()==0) {//默认存在redis中，民族总的当日热门。
            articleLists = new ArrayList<>();
            IPage<Article> iPage = new Page<>(1, 6);
            QueryWrapper<Article> qw = new QueryWrapper<>();
            qw.orderByDesc("pageview");
            IPage<Article> page = articleService.page(iPage, qw);
            List<Article> articles = page.getRecords();
            for (Article article : articles) {
                VOArticleList voArticleList = new VOArticleList();
                DataChanges.fromArticleToVOArticleList(article, voArticleList);
                articleLists.add(voArticleList);
            }
            if (articleLists.size() != 0) {
                redisService.put(CommonURL.MainPageArticle, articleLists, 1);//放入redis缓存中
            }
        }
        return articleLists;
    }
}
